package com.mmlc.meimei.lichengkongjian.shoppingbag;

import android.app.AlertDialog;
import android.content.ContentResolver;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.androidnetframe.httputil.BaseRequestFilterLayer;
import com.androidnetframe.responsejavabean.RequestError;
import com.google.gson.Gson;
import com.mmlc.inter.InterActivity;
import com.mmlc.meimei.lichengkongjian.Adapter.ShopOrderInfoAdapter;
import com.mmlc.meimei.lichengkongjian.App;
import com.mmlc.meimei.lichengkongjian.R;
import com.mmlc.meimei.lichengkongjian.dialog.CenterDialog;
import com.mmlc.network.filter.SubmitRequestFilter;
import com.mmlc.network.filter.UploadImgRequestFilter;
import com.mmlc.network.responsebean.ShopOrderPayTypeResponseBean;
import com.mmlc.network.responsebean.SubmitResponseBean;
import com.mmlc.utils.ImageTools;
import com.mmlc.utils.ToastUtils;
import com.mmlc.widget.MyListView;

import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.x;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;

import butterknife.ButterKnife;
import butterknife.InjectView;

public class ShopOrderActivity extends InterActivity implements View.OnClickListener {

    @InjectView(R.id.iv_back)
    ImageView mIvBack;
    @InjectView(R.id.rl_title)
    RelativeLayout mRlTitle;
    @InjectView(R.id.tv_name)
    TextView mTvName;
    @InjectView(R.id.tv_pay_type)
    TextView mTvPayType;
    @InjectView(R.id.container_list)
    MyListView mContainerList;
    @InjectView(R.id.iv_photo)
    ImageView mIvPhoto;
    @InjectView(R.id.iv_module)
    ImageView mIvModule;
    @InjectView(R.id.tv_done)
    TextView mTvDone;
    @InjectView(R.id.activity_pay_type)
    LinearLayout mActivityPayType;

    private static final int TAKE_PICTURE = 0;
    private static final int CHOOSE_PICTURE = 1;


    @Override
    protected int initContentView() {
        return R.layout.activity_shop_order;
    }

    public String imgSavedPath;
    ShopOrderInfoAdapter adapter;
    ViewGroup rootView;
    TextView tv_orderPrice;

    @Override
    protected void initView() {
        ButterKnife.inject(this);
        rootView = (ViewGroup) findViewById(R.id.rootView);
        tv_orderPrice = (TextView) findViewById(R.id.tv_orderPrice);


        mIvPhoto.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                selectPhoto();
            }
        });

        mIvBack.setOnClickListener(this);

        getdataFromIntent();
        String shop_name = App.user.getShopName();
        if (shop_name != null) {
            mTvName.setText(shop_name);
        }
        if (shop_name != null) {
            mTvPayType.setText(pay_method);
        }
        if (sample_img != null) {
            x.image().bind(mIvModule,sample_img);
            mIvModule.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    showBigImage(sample_img,false,1);
                }
            });
        }
        if (shop_voucher != null) {
            adapter = new ShopOrderInfoAdapter(this, shop_voucher);

            mContainerList.setAdapter(adapter);
        }

        mTvDone.setOnClickListener(this);

        //设置商品金额
        tv_orderPrice.setText(shop_Price);
    }

    private void showBigImage(String imgPath, boolean cache,int type) {
        final CenterDialog alertDialog = new CenterDialog(ShopOrderActivity.this);
        alertDialog.setView(R.layout.dialog_showbigimg);
        View view = alertDialog.getContentView();
        ImageView iv_photo = (ImageView) view.findViewById(R.id.iv_photo);

        if(cache){

            x.image().clearMemCache();
        }
        x.image().bind(iv_photo, imgPath);

        TextView bt_reSelect = (TextView) view.findViewById(R.id.bt_reSelect);
        bt_reSelect.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                reTakePhoto();
                if (alertDialog.dialog.isShowing()) {
                    alertDialog.dialog.dismiss();
                }
            }
        });
        TextView bt_btClose = (TextView) view.findViewById(R.id.bt_btClose);
        bt_btClose.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (alertDialog.dialog.isShowing()) {
                    alertDialog.dialog.dismiss();
                }
            }
        });

        if(type == 1){//不需要展示重拍
            bt_reSelect.setVisibility(View.GONE);
        }else if(type == 0){//展示重拍
            bt_reSelect.setVisibility(View.VISIBLE);
        }

        alertDialog.show();
    }

    String pay_method;
    String sample_img;
    String pay_code;
    String shop_Price;
    ArrayList<ShopOrderPayTypeResponseBean.DataBean.ExtInfoBean> shop_voucher;

    private void getdataFromIntent() {
        Intent intent = getIntent();
        pay_method = intent.getStringExtra("pay_name");
        pay_code = intent.getStringExtra("pay_code");
        sample_img = intent.getStringExtra("sample_img");
        shop_Price = intent.getStringExtra("shop_Price");
        shop_voucher = intent.getParcelableArrayListExtra("shop_voucher");
    }

    private void selectPhoto() {
        if (hasSelectPhoto) {//如果已有照片，直接展示大图
            showBigImage(imgSavedPath,true,0);
            return;
        }


        AlertDialog.Builder builder = new AlertDialog.Builder(activity);
        builder.setTitle("图片来源");
        builder.setNegativeButton("取消", null);
        builder.setItems(new String[]{"拍照"}, new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                switch (which) {
                    case 0://拍照
                        reTakePhoto();
                        break;

                    /*case 1://相册
                        Intent openAlbumIntent = new Intent(Intent.ACTION_GET_CONTENT);
                        openAlbumIntent.setType("image*//*");
                        startActivityForResult(openAlbumIntent, CHOOSE_PICTURE);
                        break;*/

                    default:
                        break;
                }
            }
        });
        builder.create().show();
    }

    private void reTakePhoto() {
        //图片保存路径
        imgSavedPath = new File(Environment.getExternalStorageDirectory(), "employee_order_image.jpg").getAbsolutePath();

        Intent openCameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        Uri imageUri = Uri.fromFile(new File(imgSavedPath));
        //指定照片保存路径（  SD卡），image.jpg为一个临时文件，每次拍照后这个图片都会被替换
        openCameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
        startActivityForResult(openCameraIntent, TAKE_PICTURE);
    }

    private static final int SCALE = 5;//照片缩小比例
    String currentHeadPhoto = null;

    boolean hasSelectPhoto;

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case TAKE_PICTURE:
                    hasSelectPhoto = true;
                    Bitmap bitmap = BitmapFactory.decodeFile(imgSavedPath);
                    Bitmap newBitmap = ImageTools.zoomBitmap(bitmap, bitmap.getWidth() / SCALE, bitmap.getHeight() / SCALE);
                    currentHeadPhoto = imgSavedPath;
                    //由于Bitmap内存占用较大，这里需要回收内存，否则会报out of memory异常
                    bitmap.recycle();

                    //将处理过的图片显示在界面上，并保存到本地
                    //x.image().bind(mIvPhoto,imgSavedPath);

                    mIvPhoto.setImageBitmap(newBitmap);
                    // ImageTools.displayCircle(mIvPhoto, imgSavedPath, R.drawable.avatar_default, true);

                    ImageTools.savePhotoToSDCard(newBitmap, Environment.getExternalStorageDirectory().getAbsolutePath(), String.valueOf(System.currentTimeMillis()));
                    break;

                case CHOOSE_PICTURE:
                    ContentResolver resolver = getContentResolver();
                    //照片的原始资源地址
                    Uri originalUri = data.getData();
                    try {
                        //使用ContentProvider通过URI获取原始图片
                        Bitmap photo = MediaStore.Images.Media.getBitmap(resolver, originalUri);
                        if (photo != null) {
                            //为防止原始图片过大导致内存溢出，这里先缩小原图显示，然后释放原始Bitmap占用的内存
                            Bitmap smallBitmap = ImageTools.zoomBitmap(photo, photo.getWidth() / SCALE, photo.getHeight() / SCALE);
                            //释放原始图片占用的内存，防止out of memory异常发生
                            photo.recycle();
                            mIvPhoto.setImageBitmap(smallBitmap);

                            String path = ImageTools.savePhotoToSDCard(smallBitmap, Environment.getExternalStorageDirectory().getAbsolutePath(), String.valueOf(System.currentTimeMillis()));
                            //将处理过的图片显示在界面上，并保存到本地
                            currentHeadPhoto = path;
                            ImageTools.displayCircle(mIvPhoto, path, R.drawable.avatar_default, true);
                        }
                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    break;
            }
        }
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.tv_done:
                processCommit();
                break;
        }
    }

    private void processCommit() {
        HashMap<String, String> hash = new HashMap<>();
        for (int i = 0; i < shop_voucher.size(); i++) {
            String key = shop_voucher.get(i).getKey();
            EditText input = (EditText) mContainerList.getChildAt(i).findViewById(R.id.et_input);
            String s = input.getText().toString();
            hash.put(key, s);
        }
        Gson gson = new Gson();
        String voucherJson = gson.toJson(hash);

        if (imgSavedPath == null) {
            ToastUtils.showToast("请拍照");
            return;
        }
        ImageTools.compressImage(3, imgSavedPath);

        /*Bitmap bitmap = BitmapFactory.decodeFile(imgSavedPath);
        String str = ImageTools.savePhotoToSDCard(bitmap, Environment.getExternalStorageDirectory().getAbsolutePath(),"tmpUpload");*/

        commitPhoto(imgSavedPath, voucherJson);

     /*   Bitmap bitmap = BitmapFactory.decodeFile(imgSavedPath);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 70, baos);
     //   String img = new String(baos.toByteArray());
        String img = baos.toString();*/


    }

    private void commitPhoto(String imgSavedPath, final String voucherJson) {

        UploadImgRequestFilter imgFilter = new UploadImgRequestFilter(this);
        imgFilter.offerErrorParams(rootView);
        imgFilter.isTransparence = true;
        imgFilter.requestParams.addBodyParameter("imgFile", new File(imgSavedPath));
        imgFilter.sendRequest(new BaseRequestFilterLayer.AccessResultFromFilter<String>() {
            @Override
            public void onSuccess(String result) {

                try {
                    JSONObject jsonObject = new JSONObject(result);
                    JSONObject data = jsonObject.getJSONObject("data");
                    commitOrder(data.optString("path"), voucherJson);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailed(View errorLayout, RequestError serverError, int failedType) {
                ToastUtils.showToast(serverError.mess);
            }
        });
    }

    private void commitOrder(String s, String voucherJson) {
        SubmitRequestFilter filter = new SubmitRequestFilter(this);
        filter.offerErrorParams(rootView);
        filter.isTransparence = true;
        filter.requestBean.pay_code = pay_code;
        filter.requestBean.cash_info = voucherJson;
        filter.requestBean.type = 1 + "";//店铺下单
        filter.requestBean.cash_img = s;//店铺下单
        filter.sendRequest(new BaseRequestFilterLayer.AccessResultFromFilter<SubmitResponseBean>() {

            @Override
            public void onSuccess(SubmitResponseBean result) {
                ToastUtils.showToast("订单提交成功");
                finish();
            }

            @Override
            public void onFailed(View errorLayout, RequestError serverError, int failedType) {
                ToastUtils.showToast(serverError.mess);
            }
        });
    }
}
